import { Color, Mesh, MeshBasicMaterial, OrthographicCamera, PlaneBufferGeometry, Scene, ShaderMaterial, Vector3, WebGLRenderer } from "three"

const canvas = document.createElement('canvas')
document.body.appendChild(canvas)
canvas.style.width = '100vw'
canvas.style.height = '100vh'

const scene = new Scene()
const renderer = new WebGLRenderer({
  antialias: true,
  canvas
})
renderer.autoClearColor = false

const camera = new OrthographicCamera(
  -1, // left
  1, // right
  1, // top
  -1, // bottom
  -1, // near
  1,  // far
)
const plane = new PlaneBufferGeometry(2, 3)

// 片元着色器
const fragmentShader = `
#include <common>

// 运行时间（以秒计）
uniform float u_time;

void main() {
  gl_FragColor = vec4(abs(sin(u_time)), 0., 0., 1.);
}
`

// const material = new MeshBasicMaterial({ color: 'red' })
const uniforms = {
  u_time: { value: 0},
}
const material = new ShaderMaterial({
  fragmentShader,
  uniforms
})
scene.add(new Mesh(plane, material))


function resizeRendererToDisplaySize(renderer: WebGLRenderer) {
  const canvas = renderer.domElement
  const width = canvas.clientWidth
  const height = canvas.clientHeight
  const needResize = canvas.width !== width || canvas.height !== height

  if (needResize) {
    renderer.setSize(width, height, false)
  }

  return needResize
}

function render(time) {
  // 转化成秒
  time *= 0.001

  resizeRendererToDisplaySize(renderer)

  // 传值给 GPU
  uniforms.u_time.value = time

  renderer.render(scene, camera)

  requestAnimationFrame(render)
}

requestAnimationFrame(render)